package OnlineExam.question;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import OnlineExam.configuration.*;
import static OnlineExam.configuration.Configure.*;


/** 
 *  Generates Question numbers in a Random way.
 */


public class RandomQuestionNumberGenerator
{
	
	/**
	 *  Generates Random numbers , returns only those generated numbers which have a 
	 *  corresponding question in the database.
	 */		

	public int[] generateQuestionNumbers (String categoryId)
	{

		// genrates random integers and returns only those numbers which have a question 
		//
		//
		Connection connection = null;
		int allNumbers[] = null;

		try
		{
			connection = DriverManager.getConnection (url, username, password);
			Statement statement = connection.createStatement();
		
			String query = "select TestLength from Category where CategoryId= '" + categoryId +"'" ;
			ResultSet resultSet = statement.executeQuery(query);
			
			int numb = 0;
			
			if (resultSet.next())
			{
				numb = resultSet.getInt ("TestLength");	
			}
		
			String lengthQuery = "select max(Number) from QuestionBank";
			ResultSet rSet = statement.executeQuery (lengthQuery);

			int length = 0;

			if (rSet.next())
			{
				length = Integer.parseInt (rSet.getString ("max(Number)"));
			}
		
			Random R=new Random();
		
			Set numbers = new HashSet ();
			allNumbers = new int [numb];
			int randNumber;
		
			for(int x=0;x<numb;x++)
			{
				while (true)
				{
					randNumber=R.nextInt(length);
					randNumber++;
				
					if((!(numbers.contains (randNumber))) && (questionExists (connection,randNumber, categoryId)))
					{
						allNumbers[x] = randNumber;
						numbers.add (randNumber);
						break;
					}
				}
			}
			return allNumbers;
		}
		catch (SQLException sqle )
		{
			System.out.println ("SQLException.." + sqle);
			return allNumbers;
		}
	}


	/**
	 *  For a random number generated, it checks if there exists a question in the database.
	 */


	private boolean questionExists (Connection connection, int qnumber, 
									String categoryId) throws SQLException
	{
		Statement statement = connection.createStatement ();
			
		String query = "select Number, Question from QuestionBank where CategoryId = '" + categoryId + "'" + 
						" and Number = '" + qnumber + "'";
		ResultSet resultSet = statement.executeQuery (query);
		
		if (resultSet.next())
			return true;

		else
			return false;
	}
}
